package com.study.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 *
 */
public class FluentCurator {

    private static String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
    private static RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    private static String path= "/zlx";
    private static CuratorFramework client = CuratorFrameworkFactory
            .builder()
            .connectString(connectStr)
            .sessionTimeoutMs(5000)
            .retryPolicy(retryPolicy)
            //指定命名空间
            // .namespace("")
            .build();

    public static void main(String[] args) throws InterruptedException,Exception{

        System.out.println("===================");
        client.start();
        System.out.println("===================");
        //创建节点
        client.create()
                .creatingParentContainersIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .forPath("/zlx/test1", "123456".getBytes());

        //获取节点
        byte [] res = client.getData().forPath(path+"/test1");
        System.out.println("getData forPath is: " + new String(res));

        Stat stat = new Stat();
        client.getData().storingStatIn(stat).forPath(path + "/test1");
        System.out.println(stat);

        //修改节点
        client.setData().withVersion(stat.getVersion()).forPath(path + "/test1", "test123456".getBytes());
        try{
            client.setData().withVersion(stat.getVersion()).forPath(path + "/test1", "test123456".getBytes());
        }catch (Exception e){
            System.out.println("Exception e is :" + e.getMessage());
        }

        System.out.println(new String(client.getData().forPath(path + "/test1")));

        //递归删除节点,并递归删除其所有子节点
        client.delete()
                .deletingChildrenIfNeeded()
                .forPath("/zlx");
        //删除一个节点，强制保证删除
        //client.delete().guaranteed().forPath("/zlx");
        Thread.sleep(Integer.MAX_VALUE);
    }
}
